package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.SeckillVoucher;
import com.hmdp.entity.Voucher;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherMapper;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisIdWorker;
import com.hmdp.utils.SimpleRedisLock;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.stream.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private ISeckillVoucherService seckillVoucherService;
    @Autowired
    private RedisIdWorker redisIdWorker;
    @Resource
    private RedissonClient redissonClient;
    private static DefaultRedisScript<Long> SECKILL_SCRIPT;
    static {
        SECKILL_SCRIPT = new DefaultRedisScript<>();
        SECKILL_SCRIPT.setLocation(new ClassPathResource("seckill.lua"));
        SECKILL_SCRIPT.setResultType(Long.class);
    }

    //秒杀订单的线程池
    private static  final ExecutorService SECKILL_ORDER_EXECUTOR = Executors.newSingleThreadExecutor();
    @PostConstruct
    private void init(){
        SECKILL_ORDER_EXECUTOR.submit(new voucherOrderHandle());
    }
      private class voucherOrderHandle implements Runnable{
        String queueName = "stream.orders";
          @Override
          public void run() {
              while (true){
                  //获取队列中的订单信息
                  try {
                      //1 获取队列中的订单信息 XREADGROUP GROUP g1 c1 COUNT 1 BLOCK 2000 STREAMS stream.orders >
                      List<MapRecord<String, Object, Object>> list = redisTemplate.opsForStream().read(
                              Consumer.from("g1", "c1"),
                              StreamReadOptions.empty().count(1).block(Duration.ofSeconds(2)),
                              StreamOffset.create(queueName, ReadOffset.lastConsumed())
                      );
                      //2 判断消息是否获取成功
                      // 2.1 如果消息获取失败 说明没有消息 继续下一次循环
                      if (list == null || list.isEmpty()){
                          continue;
                      }
                      //解析消息中的订单信息
                      MapRecord<String, Object, Object> record = list.get(0);
                      Map<Object, Object> value = record.getValue();
                      VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(value, new VoucherOrder(), true);
                      //3 如果 获取成功 可以下单
                      createVoucherOder(voucherOrder);
                      //4 ACK确认
                      redisTemplate.opsForStream().acknowledge("s1", "g1", record.getId());
                     // handleVoucherOrder(voucherOrder);
                  } catch (Exception e) {
                      log.info(e.getMessage());
                      //处理异常消息
                      handlePendingList();
                  }
              }
          }

          private void handlePendingList() {
              while (true){
                  try {
                      //EADGROUP GROUP g1 c1 COUNT 1  STREAMS s1 0
                      List<MapRecord<String, Object, Object>> list = redisTemplate.opsForStream().read(
                              Consumer.from("g1", "c1"),
                              StreamReadOptions.empty().count(1),
                              StreamOffset.create(queueName,ReadOffset.from("0"))
                      );
                      if (list == null || list.isEmpty()){
                          break;
                      }
                      //解析消息中的订单信息
                      MapRecord<String, Object, Object> record = list.get(0);
                      Map<Object, Object> value = record.getValue();
                      VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(value, new VoucherOrder(), true);
                      //3 如果 获取成功 可以下单
                      createVoucherOder(voucherOrder);
                      //4 ACK确认
                      redisTemplate.opsForStream().acknowledge("s1", "g1", record.getId());
                  } catch (Exception e) {
                      e.printStackTrace();
                      try {
                          Thread.sleep(20);
                      } catch (InterruptedException ex) {
                          ex.printStackTrace();
                      }
                  }
              }
          }
      }

  /*    //阻塞队列
    private BlockingQueue<VoucherOrder> orderTask = new ArrayBlockingQueue<>(1024 * 1024);
    private class voucherOrderHandle implements Runnable{
        @Override
        public void run() {
            while (true){
                //获取队列中的订单信息
                try {
                    VoucherOrder voucherOrder = orderTask.take();
                    //处理订单
                    handleVoucherOrder(voucherOrder);
                } catch (Exception e) {
                    e.printStackTrace();
                    log.info(e.getMessage());
                }
            }
        }
    }*/
    private IVoucherOrderService proxy;
    private void handleVoucherOrder(VoucherOrder voucherOrder) {
        RLock lock = redissonClient.getLock("lock:order:" + voucherOrder.getUserId());
        boolean isLock = lock.tryLock();
        if (!isLock){//获取锁失败
            log.info("不允许重复下单");
            return;
        }
        try {
            proxy.createVoucherOder(voucherOrder);
        } finally {
            lock.unlock();
        }
    }
    @Override
    public Result seckillVoucher(Long voucherId) {
        //获取用户
        Long userId = UserHolder.getUser().getId();

        long orderId = redisIdWorker.nextId("order");
        //执行lua脚本
        Long result = redisTemplate.execute(
                SECKILL_SCRIPT,
                Collections.emptyList(),
                voucherId.toString(), userId.toString(),String.valueOf(orderId)
        );
        //判断是否为0
        int r = result.intValue();
        if (r != 0){
            //不为0 代表没有购买资格，为0有购买资格 把下单信息保存到阻塞队列中
            return Result.fail(r==1 ? "库存不足":"不能重复下单");
        }


       /* // TODO 保存阻塞队列
        //.创建订单
        //.创建订单
        VoucherOrder voucherOrder = new VoucherOrder();
        // 订单id
        voucherOrder.setId(orderId);
        // .用户id
        voucherOrder.setUserId(userId);
        // .代金券id
        voucherOrder.setVoucherId(voucherId);
        orderTask.add(voucherOrder);*/
        //获取代理对象
        proxy = (IVoucherOrderService) AopContext.currentProxy();
        //返回订单Id
        return Result.ok(orderId);
    }
/*    public Result seckillVoucher(Long voucherId) {
        SeckillVoucher seckillVoucher = seckillVoucherService.getById(voucherId);
        if (ObjectUtils.isEmpty(seckillVoucher)){
            return Result.fail("该秒杀不存在！");
        }
        // 2.判断秒杀是否开始
        if (seckillVoucher.getBeginTime().isAfter(LocalDateTime.now())){
            return Result.fail("秒杀未开始！");
        }
        //3.判断秒杀是否结束
        if (seckillVoucher.getEndTime().isBefore(LocalDateTime.now())){
            return Result.fail("秒杀已结束！");
        }
        //4.判断库存是否充足
        if (seckillVoucher.getStock() <= 0 ){
            return Result.fail("库存不足");
        }
        Long userId = UserHolder.getUser().getId();

        //创建锁对象
   *//*     SimpleRedisLock simpleRedisLock = new SimpleRedisLock("order:" + userId, redisTemplate);
        boolean isLock = simpleRedisLock.tryLock(1200);*//*
        //换成分布式锁
        RLock lock = redissonClient.getLock("lock:order:" + userId);
        boolean isLock = lock.tryLock();
        if (!isLock){//获取锁失败
            return Result.fail("一人只能下一单！");
        }
        try {
            IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
            return proxy.createVoucherOder(voucherId);
        } finally {
            lock.unlock();
        }
     *//*   synchronized (userId.toString().intern()) {
            IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
            return proxy.createVoucherOder(voucherId);
        }*//*
    }*/
    @Transactional
    public void createVoucherOder(VoucherOrder voucherOrder) {
        Long userId = voucherOrder.getUserId();

        //一人一单校验
        Integer count = lambdaQuery()
                .eq(VoucherOrder::getUserId, userId)
                .eq(VoucherOrder::getVoucherId,voucherOrder.getVoucherId())
                .count();
        if (count > 0){
           log.info("一人只能卖一单");
           return ;
        }
        boolean success = seckillVoucherService.lambdaUpdate()
                .setSql("stock = stock - 1")
                // .eq(SeckillVoucher::getStock,seckillVoucher.getStock())//乐观锁
                .gt(SeckillVoucher::getStock,0)//乐观锁
                .eq(SeckillVoucher::getVoucherId, voucherOrder.getVoucherId())
                .update();
        if (!success){
            //扣减库存
            log.info("库存不足");
            return;
        }
        //5.创建订单
        //6.创建订单
        save(voucherOrder);
    }
   /* @Transactional
    public Result createVoucherOder(Long voucherId) {
        Long userId = UserHolder.getUser().getId();
        long orderId;

        //一人一单校验
        Integer count = lambdaQuery().eq(VoucherOrder::getUserId, userId).count();
        if (count > 0){
            return Result.fail("一人只能抢一单！");
        }
        boolean success = seckillVoucherService.lambdaUpdate()
                .setSql("stock = stock - 1")
                // .eq(SeckillVoucher::getStock,seckillVoucher.getStock())//乐观锁
                .gt(SeckillVoucher::getStock,0)//乐观锁
                .eq(SeckillVoucher::getVoucherId, voucherId)
                .update();
        if (!success){
            //扣减库存
            return Result.fail("库存不足！");
        }
        //5.创建订单
        //6.创建订单
        VoucherOrder voucherOrder = new VoucherOrder();
        // 6.1.订单id
        orderId = redisIdWorker.nextId("order");
        voucherOrder.setId(orderId);
        // 6.2.用户id

        voucherOrder.setUserId(userId);
        // 6.3.代金券id
        voucherOrder.setVoucherId(voucherId);
        save(voucherOrder);
        return Result.ok(orderId);
    }*/
}
